package com.hmily.dubbo.consumer.sync;

import com.hmily.dubbo.api.bean.UserInfo;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.io.UnsafeByteArrayInputStream;
import org.apache.dubbo.common.io.UnsafeByteArrayOutputStream;
import org.apache.dubbo.common.serialize.Serialization;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.service.GenericService;

import java.io.IOException;

import static org.apache.dubbo.rpc.Constants.GENERIC_KEY;

/**
 * <h1>泛化调用 -- OutputStream 输出流类型传参调用.</h1>
 *
 * @author hmilyylimh
 * ^_^
 * @version 0.0.1
 * ^_^
 * @date 2021-11-01
 */
public class GenericOutStreamConsumerApplication {

    public static void main(String[] args) throws Exception {
        // 设置应用服务名称
        ApplicationConfig applicationConfig = new ApplicationConfig("dubbo-consumer");
        // 设置注册中心的地址
        RegistryConfig registryConfig = new RegistryConfig("zookeeper://127.0.0.1:2181");

        // 创建引用 org.apache.dubbo.rpc.service.GenericService 这个服务的对象
        ReferenceConfig<GenericService> referenceConfig = new ReferenceConfig<>();
        referenceConfig.setApplication(applicationConfig);
        referenceConfig.setRegistry(registryConfig);
        referenceConfig.setCheck(false);

        referenceConfig.setInterface("com.hmily.dubbo.api.UserQueryFacade");
        // referenceConfig.setGeneric(true);
        referenceConfig.setGeneric("nativejava");
        RpcContext.getContext().setAttachment("generic", "nativejava");

        /*******************************/
        /** 模拟别人给过来的字节数组 start **/
        /*******************************/
        UserInfo userInfo = new UserInfo();
        userInfo.setId("G314");
        userInfo.setName("hmilyylimh");
        userInfo.setSex("M");
        // 直接拿到引用的代理对象，然后进行远程调用
        UnsafeByteArrayOutputStream out = new UnsafeByteArrayOutputStream();
        ExtensionLoader.getExtensionLoader(Serialization.class).getExtension("nativejava")
                .serialize(null, out).writeObject(userInfo);
        /*******************************/
        /** 模拟别人给过来的字节数组 end  **/
        /*******************************/

        GenericService genericService = referenceConfig.get();
        Object result = genericService.$invoke("queryUserInfo",
                new String[]{"com.hmily.dubbo.api.bean.UserInfo"},
                new Object[]{out.toByteArray()});

        // 打印结果
        UnsafeByteArrayInputStream in = new UnsafeByteArrayInputStream((byte[])result);
        result = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension("nativejava")
                .deserialize(null, in).readObject();
        System.out.println(result);

        // 阻塞等待
        System.in.read();
    }
}
